(function() {
	var $ = require(L('$'));

	exports.create = function(title, nameValuePairs, selectedValue, onItemSelectedHandler) {
		nameValuePairs = nameValuePairs || new Array();
		nameValuePairs.push($.model('name_value')('Cancel', -2));

		var selectedIndex = -1;
		var nameList = new Array();
		var dialog = Ti.UI.createOptionDialog({
			options : nameList,
			destructive : -1,			
			title : title || '',
			cancel : nameValuePairs.length - 1
		});
		
		dialog.addEventListener('click', function(e) {
			if (e.index >= 0 && onItemSelectedHandler) {
				var nameValuesPairs = e.source.nameValuePairs;
				if (nameValuePairs && nameValuePairs[e.index].name != 'Cancel') {
					e.source.destructive = parseInt(e.index);
					onItemSelectedHandler(nameValuePairs[e.index]);
				}
			}
		});
		dialog.updateDataSource = function(nameValuePairs, selectedValue) {
			var nameList = new Array();
			var selectedIndex = -1;
			if (!$.isNull(nameValuePairs)) {
				for (var i = 0, j = nameValuePairs.length; i < j; i++) {
					var item = nameValuePairs[i];
					if (item && item.name) {
						nameList.push(item.name);
						if (item.value === selectedValue) {
							selectedIndex = i;
						}
					}
				}
			}
			dialog.options = nameList;
			dialog.selectedIndex = selectedIndex;
			dialog.destructive = selectedIndex;
			dialog.nameValuePairs = nameValuePairs;
		};
		dialog.updateDataSource(nameValuePairs, selectedValue);

		return dialog;
	};
})();
